<template>
  <div>
    <el-card class="box-card">
      <!--  -->

      <el-button
        @click="addTrademark"
        class="button"
        type="primary"
        size="default"
        icon="Plus"
        style="margin: 10px 0px"
      >
        添加品牌
      </el-button>
      <!-- 展示表格 -->
      <el-table style="width: 100%" border :data="trademarkArr">
        <el-table-column type="index" label="序号" width="80%" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌logo">
          <template #="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="品牌操作">
          <template #="{ row, index }">
            <el-button
              type="primary"
              icon="Edit"
              @click="UpdatedTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定删除${row.tmName}品牌吗？`"
              width="250px"
              @confirm="removeTradeMark(row)"
            >
              <template #reference>
                <el-button type="primary" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 
    pagination
        current-page:当前页数
        page-size:每页显示条目个数
        total	总条目数
        layout	组件布局，子组件名用逗号分隔
        background	是否为分页按钮添加背景色
     -->
      <el-pagination
        @current-change="changePagesNo"
        @size-change="changeSize"
        v-model:current-page="PagesNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 8, 15]"
        :background="true"
        layout=" prev, pager, next, jumper,->,total, sizes,"
        :total="total"
      />
    </el-card>
    <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
    <!-- 
            v-model:属性用户控制对话框的显示与隐藏的 true显示 false隐藏
             title:设置对话框左上角标题
        -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        :rules="rules"
        style="width: 80%"
        :model="trademarkParams"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
          <el-upload
            class="avatar-uploader"
            action="http://sph-api.atguigu.cn/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'

import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/trademark'
import type { ResTrademark, TrademarkData } from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus'
//当前页码
let PagesNo = ref<number>(1)
//每一页有多少数据
let limit = ref<number>(3)
//已有品牌的总数、
let total = ref<number>(3)
//存储已有品牌的数据
let trademarkArr = ref<ResTrademark[]>()
//存储已有品牌的数据
let dialogFormVisible = ref<boolean>(false)
let trademarkParams = reactive<ResTrademark>({
  tmName: '',
  logoUrl: '',
})
let formRef = ref()
//获取已有品牌的接口封装为一个函数:在任何情况下向获取数据,调用次函数即可
const getHasTrademark = async () => {
  let res: TrademarkData = await reqHasTrademark(PagesNo.value, limit.value)
  if (res.code == 200) {
    total.value = res.data.total
    trademarkArr.value = res.data.records
  }
}
onMounted(() => {
  getHasTrademark()
})

//页码改变
const changePagesNo = () => {
  getHasTrademark()
}
const changeSize = () => {
  PagesNo.value = 1
  getHasTrademark()
}
//添加品牌
const addTrademark = () => {
  dialogFormVisible.value = true
  formRef.value?.clearValidate('logurl')
  formRef.value?.clearValidate('tmName')
}
//修改品牌
const UpdatedTrademark = (row: any) => {
  trademarkParams.id = row.id
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
  dialogFormVisible.value = true
  formRef.value?.clearValidate('logurl')
  formRef.value?.clearValidate('tmName')
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M

  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}

//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logurl')
}
//取消上传
const cancel = () => {
  dialogFormVisible.value = false
  trademarkParams.id = 0
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
}
//确定上传
const confirm = async () => {
  //在你发请求之前,要对于整个表单进行校验
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  console.log(formRef)

  await formRef.value.validate()
  let res = await reqAddOrUpdateTrademark(trademarkParams)

  if (res.code == 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: '添加品牌成功',
    })
    cancel()
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: '添加品牌失败',
    })
  }
}

//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
//表达校验
const rules = {
  tmName: [
    //required:这个字段务必校验,表单项前面出来五角星
    //trigger:代表触发校验规则时机[blur、change]
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
//气泡	点击确认按钮时触发
const removeTradeMark = async (row: any) => {
  let res = await reqDeleteTrademark(row.id)
  console.log(res)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: res.data,
    })
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader {
  border: 2px dashed rgb(121, 119, 119);
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
